#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 09:10:30
# @LastEditTime: 2025-03-14 09:10:35
# @Description: 阿里云监控系统主程序
###

import os
import sys
import logging
import configparser
from typing import Dict
from compute.ecs_monitor import ECSMonitor
from compute.ack_monitor import ACKMonitor
from database.rds_monitor import RDSMonitor
from database.redis_monitor import RedisMonitor
from network.slb_monitor import SLBMonitor

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('aliyun_monitor.log'),
        logging.StreamHandler()
    ]
)

class AliyunMonitorSystem:
    """阿里云监控系统"""
    
    def __init__(self, config_file: str = 'config.ini'):
        """初始化监控系统
        
        Args:
            config_file: 配置文件路径
        """
        self.config = self._load_config(config_file)
        self.monitors = self._init_monitors()
        
    def _load_config(self, config_file: str) -> Dict:
        """加载配置文件"""
        if not os.path.exists(config_file):
            logging.error(f"配置文件不存在: {config_file}")
            sys.exit(1)
            
        config = configparser.ConfigParser()
        config.read(config_file)
        return config
        
    def _init_monitors(self) -> Dict:
        """初始化所有监控模块"""
        return {
            'ecs': ECSMonitor(self.config),
            'ack': ACKMonitor(self.config),
            'rds': RDSMonitor(self.config),
            'redis': RedisMonitor(self.config),
            'slb': SLBMonitor(self.config)
        }
        
    def start_monitoring(self):
        """启动所有监控"""
        try:
            # 监控ECS实例
            logging.info("开始监控ECS实例...")
            self.monitors['ecs'].monitor_all_instances()
            
            # 监控ACK集群
            logging.info("开始监控ACK集群...")
            self.monitors['ack'].monitor_all_clusters()
            
            # 监控RDS实例
            logging.info("开始监控RDS实例...")
            self.monitors['rds'].monitor_all_instances()
            
            # 监控Redis实例
            logging.info("开始监控Redis实例...")
            self.monitors['redis'].monitor_all_instances()
            
            # 监控SLB实例
            logging.info("开始监控SLB实例...")
            self.monitors['slb'].monitor_all_instances()
            
            logging.info("所有监控任务已启动")
            
        except Exception as e:
            logging.error(f"监控系统启动失败: {e}")
            sys.exit(1)
            
    def check_resource_status(self):
        """检查所有资源状态"""
        status = {}
        
        # 检查ECS状态
        ecs_instances = self.monitors['ecs'].list_instances()
        status['ecs'] = {
            'total': len(ecs_instances),
            'instances': [{
                'id': inst['InstanceId'],
                'name': inst.get('InstanceName', ''),
                'status': inst['Status']
            } for inst in ecs_instances]
        }
        
        # 检查ACK集群状态
        ack_clusters = self.monitors['ack'].list_clusters()
        status['ack'] = {
            'total': len(ack_clusters),
            'clusters': [{
                'id': cluster['cluster_id'],
                'name': cluster.get('name', ''),
                'status': cluster['state']
            } for cluster in ack_clusters]
        }
        
        # 检查RDS状态
        rds_instances = self.monitors['rds'].list_instances()
        status['rds'] = {
            'total': len(rds_instances),
            'instances': [{
                'id': inst['DBInstanceId'],
                'name': inst.get('DBInstanceDescription', ''),
                'status': inst['DBInstanceStatus']
            } for inst in rds_instances]
        }
        
        # 检查Redis状态
        redis_instances = self.monitors['redis'].list_instances()
        status['redis'] = {
            'total': len(redis_instances),
            'instances': [{
                'id': inst['InstanceId'],
                'name': inst.get('InstanceName', ''),
                'status': inst['InstanceStatus']
            } for inst in redis_instances]
        }
        
        # 检查SLB状态
        slb_instances = self.monitors['slb'].list_load_balancers()
        status['slb'] = {
            'total': len(slb_instances),
            'instances': [{
                'id': inst['LoadBalancerId'],
                'name': inst.get('LoadBalancerName', ''),
                'status': inst['LoadBalancerStatus']
            } for inst in slb_instances]
        }
        
        return status

def main():
    """主函数"""
    # 获取脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_file = os.path.join(script_dir, 'config.ini')
    
    # 初始化监控系统
    monitor_system = AliyunMonitorSystem(config_file)
    
    # 检查资源状态
    logging.info("检查资源状态...")
    status = monitor_system.check_resource_status()
    for resource_type, info in status.items():
        logging.info(f"{resource_type.upper()} 资源状态:")
        logging.info(f"- 总数: {info['total']}")
        for instance in info['instances']:
            logging.info(f"- {instance['name']}({instance['id']}): {instance['status']}")
            
    # 启动监控
    logging.info("启动监控系统...")
    monitor_system.start_monitoring()

if __name__ == "__main__":
    main()
